#!/usr/bin/env python3
"""
Flowable 流程部署验证脚本
用于验证所有流程是否已正确部署
"""

import sys
import os
import requests
from requests.auth import HTTPBasicAuth
from typing import List, Dict, Optional

# 配置
# 注意：如果 Flowable UI 和 REST API 在同一端口，使用 8080
# 如果分开部署，REST API 通常在 8081
FLOWABLE_URL = os.getenv("FLOWABLE_URL", "http://localhost:8081/flowable-rest")
FLOWABLE_USER = os.getenv("FLOWABLE_USER", "admin")
FLOWABLE_PASS = os.getenv("FLOWABLE_PASS", "test")

# 期望的流程定义
EXPECTED_PROCESSES = [
    "purchaseApproval",      # 采购申请审批流程
    "paymentApproval",        # 付款申请审批流程
    "materialApplyApproval",  # 材料申领审批流程
    "leaveApproval",          # 请假/加班申请审批流程
    "vehicleApplyApproval"    # 用车申请审批流程
]


class FlowableVerifier:
    """Flowable 部署验证器"""
    
    def __init__(self, base_url: str, username: str, password: str):
        self.base_url = base_url.rstrip('/')
        self.auth = HTTPBasicAuth(username, password)
        self.session = requests.Session()
        self.session.auth = self.auth
    
    def check_service_health(self) -> bool:
        """检查 Flowable 服务是否可用"""
        try:
            url = f"{self.base_url}/service/management/engine"
            response = self.session.get(url, timeout=5)
            return response.status_code == 200
        except Exception as e:
            print(f"❌ 无法连接到 Flowable 服务: {e}")
            return False
    
    def get_process_definitions(self) -> List[Dict]:
        """获取所有已部署的流程定义"""
        try:
            url = f"{self.base_url}/service/repository/process-definitions"
            response = self.session.get(url)
            response.raise_for_status()
            data = response.json()
            return data.get('data', [])
        except Exception as e:
            print(f"❌ 获取流程定义失败: {e}")
            return []
    
    def verify_processes(self) -> Dict[str, bool]:
        """验证所有期望的流程是否已部署"""
        processes = self.get_process_definitions()
        deployed_keys = {p.get('key') for p in processes}
        
        results = {}
        for expected_key in EXPECTED_PROCESSES:
            results[expected_key] = expected_key in deployed_keys
        
        return results
    
    def print_results(self, results: Dict[str, bool]):
        """打印验证结果"""
        print("\n" + "=" * 60)
        print("Flowable 流程部署验证结果")
        print("=" * 60)
        
        all_passed = True
        for process_key, is_deployed in results.items():
            status = "✅" if is_deployed else "❌"
            print(f"{status} {process_key}")
            if not is_deployed:
                all_passed = False
        
        print("=" * 60)
        
        if all_passed:
            print("\n✅ 所有流程已成功部署！")
            return True
        else:
            print("\n❌ 部分流程未部署，请检查部署日志")
            return False


def main():
    """主函数"""
    print("正在验证 Flowable 服务状态...")
    
    verifier = FlowableVerifier(FLOWABLE_URL, FLOWABLE_USER, FLOWABLE_PASS)
    
    # 检查服务健康状态
    if not verifier.check_service_health():
        print("\n❌ Flowable 服务不可用，请确保服务已启动")
        print(f"   检查地址: {FLOWABLE_URL}")
        sys.exit(1)
    
    print("✅ Flowable 服务连接成功")
    
    # 验证流程部署
    results = verifier.verify_processes()
    success = verifier.print_results(results)
    
    sys.exit(0 if success else 1)


if __name__ == "__main__":
    main()

